<template>
  <form @submit.prevent="submit">
    <input type="email" placeholder="what's your email"
           v-model="name"
           @blur="v.name.$touch()"
           :class="{error: v.name.$error}"
    >
    <div v-if="v.name.$error">
      Error custom message
      <p v-if="v.name.email.$invalid" class="errorMessage">Please enter a valid email</p>
      <p v-if="v.name.required.$invalid" class="errorMessage">Email is required</p>
    </div>

<!--    <div v-if="v.name.$errors.length"> ;name error-->
    <template v-if="v.$errors.length">All error default message</template>
    <p v-for="error in v.$errors" class="errorMessage">{{error.$message}}</p>


    <div>
      <button :disabled="v.$invalid" type="submit">Submit</button>
    </div>
  </form>
<!--  {{ v.name }}-->
<!--  <hr>-->
<!--  {{ v }}-->
</template>

<script>
import {required, email} from '@vuelidate/validators'
import {useVuelidate} from '@vuelidate/core'
import {ref} from 'vue'

export default {
  name: "VuelidateExample",
  mounted() {
    console.log('xx', this.v)
  }
  ,
  setup() {
    const name = ref('df@df.com')
    const rules = {
      name: {required, email}
    }

    const v = useVuelidate(rules, {name})
    // return {name, v}
    const submit = () => {
      v.value.$touch();
      if (!v.value.$invalid) {
        console.log('Form Submit', name);
      }
    }

    return {name, v, submit}
  },
  // methods: { // 同setup方法
  //   submit() {
  //     this.v.$touch();
  //     if (!this.v.$invalid) {
  //       console.log('Form Submit', this.name);
  //     }
  //   }
  // }
}
</script>
